package main

import (
	"bufio"
	"bytes"
	"fmt"
	"log"
	"net"
	"os"
	"time"
)

func recvbig_s(port string) {
	hostPort := "0.0.0.0:" + port
	l, e := net.Listen("tcp4", hostPort)
	if e != nil {
		log.Println(e.Error())
		os.Exit(0)
	}
	for {
		conn, err := l.Accept()
		if err != nil {
			log.Println(err.Error())
			os.Exit(0)
		}
		go handleRecvbig_s(conn)
	}
}

func handleRecvbig_s(conn net.Conn) {
	defer conn.Close()
	// rootName := viper.GetString("root.name")
	// rootDes := viper.GetString("root.description")
	buffer := new(bytes.Buffer)
	for {
		fmt.Println("++++++++++")
		n, _ := buffer.ReadFrom(conn)
		fmt.Println("Normal -> , ", string(buffer.Bytes()))
		if n == 0 {
			fmt.Println("break----------")
			break
		}
		if bytes.Contains(buffer.Bytes(), []byte{'o', 'v'}) {
			fmt.Println("over----------")
			break
		}
	}
	n, err := conn.Write([]byte{'o'})
	fmt.Println(n)
	if err != nil {
		fmt.Println(err.Error())
	}
	fmt.Println("o v e r")
}

func recvbig_c(host, port string) {
	var conn net.Conn
	for {
		conn1, err := net.Dial("tcp4", host+":"+port)
		if err == nil {
			conn = conn1
			break
		}
		fmt.Println(err.Error())
		time.Sleep(time.Millisecond * 388)
	}
	defer conn.Close()
	buffer := new(bytes.Buffer)

	scanner := bufio.NewScanner(os.Stdin)
	for fmt.Print("(please input): "); scanner.Scan(); fmt.Print("(please input): ") {
		fmt.Println("|")
		fmt.Println("|")
		fmt.Println("--> ")
		buffer.Reset()
		buffer.Write(scanner.Bytes())
		if bytes.HasPrefix(buffer.Bytes(), []byte{'o', 'v', 'e', 'r'}) {
			fmt.Println("[client]-->[over]")
			conn.Write(buffer.Bytes())
			break
		}
		if bytes.HasPrefix(buffer.Bytes(), []byte{'1', '0'}) {
			for i := 0; i != 10; i++ {
				conn.Write(buffer.Bytes())
			}
			fmt.Println("[10 mode over]")
			continue
		}
		conn.Write(buffer.Bytes())
	}
	time.Sleep(time.Second * 1)
}
